use crate::error::Result;
use crate::storage::data_types::traits::{DataType, HashOperations};
use async_trait::async_trait;
use std::any::Any;
use fxhash::FxHashMap;

/// Hash data type implementation
/// 
/// Represents a Redis hash value, which is a collection of field-value pairs.
/// Equivalent to a dictionary or map in other programming languages.
/// Uses high-performance FxHashMap for optimal speed.
#[derive(Debug, Clone)]
pub struct HashType {
    data: FxHashMap<String, String>,
}

impl HashType {
    /// Create a new empty hash
    pub fn new() -> Self {
        Self {
            data: FxHashMap::default(),
        }
    }
    
    /// Create a hash from an existing FxHashMap
    pub fn from_map(data: FxHashMap<String, String>) -> Self {
        Self { data }
    }
    
    /// Get the underlying FxHashMap reference
    pub fn as_map(&self) -> &FxHashMap<String, String> {
        &self.data
    }
    
    /// Get the underlying FxHashMap mutable reference
    pub fn as_map_mut(&mut self) -> &mut FxHashMap<String, String> {
        &mut self.data
    }
    
    /// Clear all fields
    pub fn clear(&mut self) {
        self.data.clear();
    }
    
    /// Get the memory usage of the hash
    fn calculate_memory_usage(&self) -> usize {
        let base_size = std::mem::size_of::<Self>();
        let map_overhead = self.data.capacity() * std::mem::size_of::<(String, String)>();
        let content_size: usize = self.data
            .iter()
            .map(|(k, v)| k.len() + v.len())
            .sum();
        
        base_size + map_overhead + content_size
    }
}

impl Default for HashType {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl DataType for HashType {
    fn type_name(&self) -> &'static str {
        "hash"
    }
    
    fn debug_string(&self) -> String {
        format!("HashType({} fields)", self.data.len())
    }
    
    fn clone_data(&self) -> Box<dyn DataType> {
        Box::new(self.clone())
    }
    
    fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
    
    fn memory_usage(&self) -> usize {
        self.calculate_memory_usage()
    }
    
    fn as_any(&self) -> &dyn Any {
        self
    }
    
    fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }
}

impl HashOperations for HashType {
    fn hset(&mut self, field: String, value: String) -> Result<bool> {
        let is_new = !self.data.contains_key(&field);
        self.data.insert(field, value);
        Ok(is_new)
    }
    
    fn hget(&self, field: &str) -> Result<Option<String>> {
        Ok(self.data.get(field).cloned())
    }
    
    fn hdel(&mut self, field: &str) -> Result<bool> {
        Ok(self.data.remove(field).is_some())
    }
    
    fn hexists(&self, field: &str) -> Result<bool> {
        Ok(self.data.contains_key(field))
    }
    
    fn hkeys(&self) -> Result<Vec<String>> {
        Ok(self.data.keys().cloned().collect())
    }
    
    fn hvals(&self) -> Result<Vec<String>> {
        Ok(self.data.values().cloned().collect())
    }
    
    fn hgetall(&self) -> Result<FxHashMap<String, String>> {
        Ok(self.data.clone())
    }
    
    fn hlen(&self) -> Result<usize> {
        Ok(self.data.len())
    }
    
    fn hmset(&mut self, pairs: FxHashMap<String, String>) -> Result<()> {
        for (field, value) in pairs {
            self.data.insert(field, value);
        }
        Ok(())
    }
    
    fn hmget(&self, fields: &[String]) -> Result<Vec<Option<String>>> {
        let mut result = Vec::with_capacity(fields.len());
        for field in fields {
            result.push(self.data.get(field).cloned());
        }
        Ok(result)
    }
}

impl From<FxHashMap<String, String>> for HashType {
    fn from(data: FxHashMap<String, String>) -> Self {
        Self::from_map(data)
    }
}

impl From<Vec<(String, String)>> for HashType {
    fn from(pairs: Vec<(String, String)>) -> Self {
        let mut data = FxHashMap::default();
        for (field, value) in pairs {
            data.insert(field, value);
        }
        Self::from_map(data)
    }
}

impl From<&[(String, String)]> for HashType {
    fn from(pairs: &[(String, String)]) -> Self {
        let mut data = FxHashMap::default();
        for (field, value) in pairs {
            data.insert(field.clone(), value.clone());
        }
        Self::from_map(data)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_hash_basic_operations() {
        let mut hash = HashType::new();
        
        assert!(hash.is_empty());
        assert_eq!(hash.hlen().unwrap(), 0);
        
        // Test hset
        assert!(hash.hset("field1".to_string(), "value1".to_string()).unwrap());
        assert!(!hash.hset("field1".to_string(), "new_value1".to_string()).unwrap()); // Update existing
        
        assert_eq!(hash.hlen().unwrap(), 1);
        assert!(!hash.is_empty());
    }
    
    #[test]
    fn test_hash_get_operations() {
        let mut hash = HashType::new();
        
        hash.hset("field1".to_string(), "value1".to_string()).unwrap();
        hash.hset("field2".to_string(), "value2".to_string()).unwrap();
        
        // Test hget
        assert_eq!(hash.hget("field1").unwrap(), Some("value1".to_string()));
        assert_eq!(hash.hget("field2").unwrap(), Some("value2".to_string()));
        assert_eq!(hash.hget("nonexistent").unwrap(), None);
        
        // Test hexists
        assert!(hash.hexists("field1").unwrap());
        assert!(hash.hexists("field2").unwrap());
        assert!(!hash.hexists("nonexistent").unwrap());
    }
    
    #[test]
    fn test_hash_delete_operations() {
        let mut hash = HashType::new();
        
        hash.hset("field1".to_string(), "value1".to_string()).unwrap();
        hash.hset("field2".to_string(), "value2".to_string()).unwrap();
        
        // Test hdel
        assert!(hash.hdel("field1").unwrap());
        assert!(!hash.hdel("field1").unwrap()); // Already deleted
        assert!(!hash.hdel("nonexistent").unwrap());
        
        assert_eq!(hash.hlen().unwrap(), 1);
        assert!(!hash.hexists("field1").unwrap());
        assert!(hash.hexists("field2").unwrap());
    }
    
    #[test]
    fn test_hash_keys_and_values() {
        let mut hash = HashType::new();
        
        hash.hset("field1".to_string(), "value1".to_string()).unwrap();
        hash.hset("field2".to_string(), "value2".to_string()).unwrap();
        hash.hset("field3".to_string(), "value3".to_string()).unwrap();
        
        // Test hkeys
        let mut keys = hash.hkeys().unwrap();
        keys.sort();
        assert_eq!(keys, vec!["field1", "field2", "field3"]);
        
        // Test hvals
        let mut values = hash.hvals().unwrap();
        values.sort();
        assert_eq!(values, vec!["value1", "value2", "value3"]);
    }
    
    #[test]
    fn test_hash_getall() {
        let mut hash = HashType::new();
        
        hash.hset("field1".to_string(), "value1".to_string()).unwrap();
        hash.hset("field2".to_string(), "value2".to_string()).unwrap();
        
        let all = hash.hgetall().unwrap();
        assert_eq!(all.len(), 2);
        assert_eq!(all.get("field1"), Some(&"value1".to_string()));
        assert_eq!(all.get("field2"), Some(&"value2".to_string()));
    }
    
    #[test]
    fn test_hash_multi_operations() {
        let mut hash = HashType::new();
        
        // Test hmset
        let mut pairs = FxHashMap::default();
        pairs.insert("field1".to_string(), "value1".to_string());
        pairs.insert("field2".to_string(), "value2".to_string());
        pairs.insert("field3".to_string(), "value3".to_string());
        
        hash.hmset(pairs).unwrap();
        assert_eq!(hash.hlen().unwrap(), 3);
        
        // Test hmget
        let fields = vec!["field1".to_string(), "field2".to_string(), "nonexistent".to_string()];
        let values = hash.hmget(&fields).unwrap();
        
        assert_eq!(values.len(), 3);
        assert_eq!(values[0], Some("value1".to_string()));
        assert_eq!(values[1], Some("value2".to_string()));
        assert_eq!(values[2], None);
    }
    
    #[test]
    fn test_hash_conversions() {
        // Test from FxHashMap
        let mut map = FxHashMap::default();
        map.insert("key1".to_string(), "value1".to_string());
        map.insert("key2".to_string(), "value2".to_string());
        
        let hash = HashType::from(map.clone());
        assert_eq!(hash.hlen().unwrap(), 2);
        assert_eq!(hash.hget("key1").unwrap(), Some("value1".to_string()));
        
        // Test from Vec
        let pairs = vec![
            ("key3".to_string(), "value3".to_string()),
            ("key4".to_string(), "value4".to_string()),
        ];
        
        let hash = HashType::from(pairs);
        assert_eq!(hash.hlen().unwrap(), 2);
        assert_eq!(hash.hget("key3").unwrap(), Some("value3".to_string()));
    }
    
    #[test]
    fn test_data_type_trait() {
        let hash = HashType::new();
        
        assert_eq!(hash.type_name(), "hash");
        assert!(hash.is_empty());
        assert!(hash.memory_usage() > 0);
        
        let cloned = hash.clone_data();
        assert_eq!(cloned.type_name(), "hash");
    }
}